package com.cskaoyan.service.wx.cart;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.wx.cart.CartAddBO;
import com.cskaoyan.bean.bo.wx.cart.CheckBO;
import com.cskaoyan.bean.vo.wx.cart.CartCouponVO;
import com.cskaoyan.bean.vo.wx.cart.CartTotal;
import com.cskaoyan.bean.vo.wx.cart.CartVO;
import com.cskaoyan.bean.vo.wx.cart.CheckOutVO;
import com.cskaoyan.bean.bo.wx.cart.CheckedBO;
import com.cskaoyan.bean.bo.wx.cart.UpdateCartBO;
import com.cskaoyan.bean.common.User;
import com.cskaoyan.bean.vo.wx.cart.*;
import com.cskaoyan.bean.vo.wx.coupon.WxCouponSelectlistCouponVo;
import com.cskaoyan.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

// import sun.security.util.math.intpoly.P384OrderField;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/*
 * @Auther:王贲
 * @Date:2022/9/9
 * @Description:
 * @VERSON:1.8
 */
@Service
@Transactional
public class WxCartServiceImpl implements WxCartService{

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    WxMarketCouponMapper wxMarketCouponMapper;
    //public static Integer userId = 1;


    @Autowired
    MarketSystemMapper marketSystemMapper;
    @Override
    public CartVO selectCartInfo() {
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        //获取当前的用户id
        Integer userId = getUserId();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        //通过userId查出此用户下的所有购物车信息
        List<MarketCart> cartList = marketCartMapper.selectByExample(marketCartExample);

        // TODO： 开始实现计算购物车的总数和总金额
        int goodsCount = 0;
        int checkedGoodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        BigDecimal checkedGoodsAmount = new BigDecimal(0);
        for (MarketCart marketCart : cartList) {
            //得到goods的总数
            goodsCount += marketCart.getNumber();
            //通过marketCart.getPrice()得到单价，然后与multiply(new BigDecimal(marketCart.getNumber()))得到的数量相乘 得出总价
            goodsAmount = goodsAmount.add(marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber())));
            //判断购物车中的货物是否是选择状态，如果是，就算出总数和总金额
            if (marketCart.getChecked()) {
                checkedGoodsCount += marketCart.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber())));
            }
        }
        CartTotal cartTotal = new CartTotal((short) goodsCount, (short) checkedGoodsCount, goodsAmount, checkedGoodsAmount);
        CartVO cartVO = new CartVO(cartTotal,cartList);

        return cartVO;
    }


    /**
     * @description : TODO 拿到当前用户信息的方法
     * @return java.lang.Integer
     * @author wang'ben
     * @date 2022/9/11 13:34
     */
    private static Integer getUserId() {
        Subject subject = SecurityUtils.getSubject();
        MarketUser principal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        //拿到当前用户信息的id
        Integer id = principal.getId();
        return id;
    }

    @Override
    public int addCartNum(CartAddBO cartAddBO) {
        Integer productId = cartAddBO.getProductId();
        Integer number = cartAddBO.getNumber();
        Integer goodsId = cartAddBO.getGoodsId();
        //得到当前用户id
        Integer userId = getUserId();
        //查询未删除的状态
        //product
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria proCriteria = marketGoodsProductExample.createCriteria();
        proCriteria.andDeletedEqualTo(false);
        //goods
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria goodsCriteria = marketGoodsExample.createCriteria();
        goodsCriteria.andDeletedEqualTo(false);
        //求number总数
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria numCriteria = marketCartExample.createCriteria();
        numCriteria.andDeletedEqualTo(false);
        //判断是否是当前userId
        numCriteria.andUserIdEqualTo(userId);
        Integer total = number;
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);
        for (MarketCart marketCart : marketCartList) {
            total += marketCart.getNumber();
        }

        //根据goodsId查询出所有的marketGoods
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);
        //根据productId查询出所有的marketProduct
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
        //判断库存是否足够
        int statusId = 0;
        if (number > marketGoodsProduct.getNumber()) {
            statusId = 711;
            return statusId;
        }
        //库存足够的话判断插入的商品是否已经存在在购物车内部，如果存在就只插入数量，不存在就直接插入数据
        Integer isExist = isExistGoods(userId,goodsId);
        MarketCartExample marketCartGoodsIdExample = new MarketCartExample();
        MarketCartExample.Criteria criteriaGoodsId = marketCartGoodsIdExample.createCriteria();
        criteriaGoodsId.andDeletedEqualTo(false).andUserIdEqualTo(userId).andGoodsIdEqualTo(goodsId);
        List<MarketCart> marketCartGoodsId = marketCartMapper.selectByExample(marketCartGoodsIdExample);
        //判断是否存在
        if (isExist == 1) {
            // 存在，只增加数量
            Integer numberAdd = marketCartGoodsId.get(0).getNumber() + number;
            //转为short类型
            short numAdd = numberAdd.shortValue();
            marketCartGoodsId.get(0).setNumber(numAdd);
            marketCartMapper.updateByPrimaryKeySelective(marketCartGoodsId.get(0));
        } else {
            String goodsSn = marketGoods.getId() + "";
            short numberAmount = number.shortValue();
            MarketCart marketCart = new MarketCart(null, userId, goodsId, goodsSn,
                    marketGoods.getName(), productId, marketGoodsProduct.getPrice(),numberAmount , marketGoodsProduct.getSpecifications(),
                    true, marketGoodsProduct.getUrl(), marketGoodsProduct.getAddTime(), marketGoodsProduct.getUpdateTime(), false);
            marketCartMapper.insert(marketCart);
        }

        return total;
    }

    @Override
    public CartVO deleteCartInfo(Integer[] productIds) {
        Integer userId = getUserId();

        for (Integer productId : productIds) {
            MarketCart marketCart = new MarketCart();
            marketCart.setDeleted(true);
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andProductIdEqualTo(productId);
            marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
        }
        return selectCartInfo();
    }

    @Override
    public CheckOutVO checkOutMothed(CheckBO checkBO) {
        //得到请求参数的值
        Integer cartId = checkBO.getCartId();
        Integer addressId = checkBO.getAddressId();
        Integer couponId = checkBO.getCouponId();
        Integer userCouponId = checkBO.getUserCouponId();
        Integer grouponRulesId = checkBO.getGrouponRulesId();
        Integer userId = getUserId();

        //地址信息
        //TODO： 判断接受的addressId是否大于0，如果大于0，直接返回这个addressId对应的地址
        //       如果不大于0，去选择默认的值
        MarketAddress marketAddress = null;
        if (addressId > 0) {
            marketAddress = marketAddressMapper.selectByPrimaryKey(addressId);
        } else {
            MarketAddressExample marketAddressExample = new MarketAddressExample();
            MarketAddressExample.Criteria criteria = marketAddressExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andIsDefaultEqualTo(true).andDeletedEqualTo(false);
            List<MarketAddress> marketAddresses = marketAddressMapper.selectByExample(marketAddressExample);
            //取最前面的数据作为默认的id
            if (marketAddresses.size() > 0) {
                marketAddress = marketAddresses.get(0);
                addressId = marketAddress.getId();
            }
        }

        //商品详情
        //如果cartId  小于等于0 则就将用户选中的购物车信息返回出去
        //如果cartId 大于0 将购物车表的的信息根据cartId返回出去
        List<MarketCart> marketCarts = null;
        if (cartId > 0) {
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andGoodsIdEqualTo(cartId).andDeletedEqualTo(false).andCheckedEqualTo(true);
            marketCarts = marketCartMapper.selectByExample(marketCartExample);
        } else {
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andUserIdEqualTo(userId).andDeletedEqualTo(false).andCheckedEqualTo(true);
            marketCarts = marketCartMapper.selectByExample(marketCartExample);
        }
        // TODO： 开始实现计算购物车的总数和总金额
        int goodsCount = 0;
        int checkedGoodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        BigDecimal checkedGoodsAmount = new BigDecimal(0);
        for (MarketCart marketCart : marketCarts) {
            //得到goods的总数
            goodsCount += marketCart.getNumber();
            //通过marketCart.getPrice()得到单价，然后与multiply(new BigDecimal(marketCart.getNumber()))得到的数量相乘 得出总价
            goodsAmount = goodsAmount.add(marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber())));
            //判断购物车中的货物是否是选择状态，如果是，就算出总数和总金额
            if (marketCart.getChecked()) {
                checkedGoodsCount += marketCart.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(marketCart.getPrice().multiply(new BigDecimal(marketCart.getNumber())));
            }
        }
        //得到支付总金额
        CartTotal cartTotal = new CartTotal((short) goodsCount, (short) checkedGoodsCount, goodsAmount, checkedGoodsAmount);
        BigDecimal amountPrice = cartTotal.getCheckedGoodsAmount();


        //运费
        //查找运费的最小收费价格
        String freightPriceMin = marketSystemMapper.selectFreightPriceInfo("market_express_freight_min");
        //查找运费的价格
        String freightPriceValue = marketSystemMapper.selectFreightPriceInfo("market_express_freight_value");
        BigDecimal PriceMin = new BigDecimal(freightPriceMin);
        BigDecimal PriceValue = new BigDecimal(freightPriceValue);
        BigDecimal price =new BigDecimal(0);
        if (PriceMin.compareTo(amountPrice) > 0) {
            price = price.add(PriceValue);
        }
        //优惠券
        //根据用户id 和 status去查询所有的优惠券
        List<CartCouponVO> marketCoupons = wxMarketCouponMapper.selectCouponInfo(userId,0);
        List<CartCouponVO> list = new ArrayList<>();
        for (CartCouponVO marketCoupon : marketCoupons) {
            list.add(marketCoupon);
        }
        Integer availableCouponLength = list.size();

        //计算优惠的价格
        BigDecimal couponPrice = new BigDecimal(0);

        //优惠券 如果传入的参数userCouponId小于或者等于0 代表没有指定的优惠券，直接使用默认的
        //如果传入的userCouponId大于0 则使用传进来的userCouponId的优惠券
        if (userCouponId <= 0) {
            // 默认使用第一个
            if (availableCouponLength > 0) {
                CartCouponVO couponList = list.get(0);
                couponPrice = couponList.getDiscount();
                Integer userCoupon = couponList.getId();
                Integer couponId1 = couponList.getCid();
                MarketCouponUser marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(couponId1);
            }
        } else {
            //使用指定的优惠券
            MarketCouponUser marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(couponId);
            if (marketCouponUser != null) {
                Integer couponId1 = marketCouponUser.getCouponId();
                MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId1);
                if (marketCoupon != null) {
                    couponPrice = marketCoupon.getDiscount();
                }
            }
        }

        //计算商品总价
        BigDecimal orderTotalPrice1  = new BigDecimal(0);
        BigDecimal orderTotalPrice = orderTotalPrice1.add(price).add(amountPrice).subtract(couponPrice);
        BigDecimal actualPrice = new BigDecimal(0);
        BigDecimal actualPrice1 = actualPrice.add(orderTotalPrice);
        CheckOutVO checkOutVO = new CheckOutVO(grouponRulesId, actualPrice1, orderTotalPrice, cartId, userCouponId, couponId, amountPrice, addressId, 0, marketAddress, couponPrice, availableCouponLength, price, marketCarts);
        return checkOutVO;
    }

    @Override
    public void updateCartInfo(UpdateCartBO updateCartBO) {
        Integer goodsId = updateCartBO.getGoodsId();
        Integer id = updateCartBO.getId();
        Integer number = updateCartBO.getNumber();
        Integer productId = updateCartBO.getProductId();
        Integer userId = getUserId();

        //首先根据goodsId查询所选中的商品
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(goodsId);
        //判断是否库存不足（可以显示库存永远足够，这一步可以省略）

        //将id和数量放进cart表中
        MarketCart marketCart = new MarketCart();
        marketCart.setId(id);
        short numberUpdate = number.shortValue();
        marketCart.setNumber(numberUpdate);
        //判断是否是当前用户
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteriaCart = marketCartExample.createCriteria();
        criteriaCart.andDeletedEqualTo(false).andUserIdEqualTo(userId);

        //根据更改后的数据更新购物车的数据
        marketCartMapper.updateByPrimaryKeySelective(marketCart);


    }

    /**
     * @description : TODO 选中商品
     * @return com.cskaoyan.bean.vo.wx.cart.CartVO
     * @author wang'ben
     * @date 2022/9/12 11:36
     */
    @Override
    public CartVO checkedCartInfo(CheckedBO checkedBO) {
        Integer isChecked = checkedBO.getIsChecked();
        Integer userId = getUserId();
        List<Integer> productIds = checkedBO.getProductIds();
            for (Integer productIds2 : productIds) {
                MarketCart marketCart = new MarketCart();
                if (isChecked == 1) {
                    marketCart.setChecked(true);
                } else {
                    marketCart.setChecked(false);
                }
                MarketCartExample marketCartExample = new MarketCartExample();
                MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
                criteria.andUserIdEqualTo(userId).andProductIdEqualTo(productIds2).andDeletedEqualTo(false);

                marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
            }

        return selectCartInfo();
    }

    @Override
    public int fastAddCartInfo(CartAddBO cartAddBO) {
        Integer goodsId = cartAddBO.getGoodsId();
        Integer productId = cartAddBO.getProductId();
        Integer number = cartAddBO.getNumber();
        Integer userId = getUserId();
        // WxCartServiceImpl wxCartService = new WxCartServiceImpl();
        // int total = wxCartService.addCartNum(cartAddBO);
        //查询未删除的状态
        //product
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria proCriteria = marketGoodsProductExample.createCriteria();
        proCriteria.andDeletedEqualTo(false);
        //goods
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        MarketGoodsExample.Criteria goodsCriteria = marketGoodsExample.createCriteria();
        goodsCriteria.andDeletedEqualTo(false);
        //求number总数
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria numCriteria = marketCartExample.createCriteria();
        numCriteria.andDeletedEqualTo(false);
        //判断是否是当前userId
        numCriteria.andUserIdEqualTo(userId);
        Integer total = number;
        List<MarketCart> marketCartList = marketCartMapper.selectByExample(marketCartExample);
        for (MarketCart marketCart : marketCartList) {
            total += marketCart.getNumber();
        }

        //根据goodsId查询出所有的marketGoods
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);
        //根据productId查询出所有的marketProduct
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
        //判断库存是否足够
        // int statusId = 0;
        // if (number > marketGoodsProduct.getNumber()) {
        //     statusId = 711;
        //     return statusId;
        // }
        //库存足够的话判断插入的商品是否已经存在在购物车内部，如果存在就只插入数量，不存在就直接插入数据
        Integer isExist = isExistGoods(userId,goodsId);
        MarketCartExample marketCartGoodsIdExample = new MarketCartExample();
        MarketCartExample.Criteria criteriaGoodsId = marketCartGoodsIdExample.createCriteria();
        criteriaGoodsId.andDeletedEqualTo(false).andUserIdEqualTo(userId).andGoodsIdEqualTo(goodsId);
        List<MarketCart> marketCartGoodsId = marketCartMapper.selectByExample(marketCartGoodsIdExample);
        //判断是否存在
        if (isExist == 1) {
            // 存在，只增加数量
            Integer numberAdd = marketCartGoodsId.get(0).getNumber() + number;
            //转为short类型
            short numAdd = numberAdd.shortValue();
            marketCartGoodsId.get(0).setNumber(numAdd);
            marketCartMapper.updateByPrimaryKeySelective(marketCartGoodsId.get(0));
        } else {
            String goodsSn = marketGoods.getId() + "";
            short numberAmount = number.shortValue();
            MarketCart marketCart = new MarketCart(null, userId, goodsId, goodsSn,
                    marketGoods.getName(), productId, marketGoodsProduct.getPrice(),numberAmount , marketGoodsProduct.getSpecifications(),
                    true, marketGoodsProduct.getUrl(), marketGoodsProduct.getAddTime(), marketGoodsProduct.getUpdateTime(), false);
            marketCartMapper.insert(marketCart);
        }
        return marketGoods.getId();
    }

    @Override
    public Integer goodsCountCartInfo() {
        Integer userId = getUserId();
        if (userId == null) {
            return 0;
        }
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(false);
        int goodsCount = (int) marketCartMapper.countByExample(marketCartExample);
        return goodsCount;
    }


    private Integer isExistGoods(Integer userId,Integer goodsId) {
        MarketCartExample marketCartExist = new MarketCartExample();
        MarketCartExample.Criteria criteriaExist = marketCartExist.createCriteria();
        criteriaExist.andDeletedEqualTo(false).andUserIdEqualTo(userId);

        List<MarketCart> marketCartExists = marketCartMapper.selectByExample(marketCartExist);
        for (MarketCart cartExist : marketCartExists) {
            if (cartExist.getGoodsId().equals(goodsId)) {
                // 相同返回1
                return 1;
            }
        }
        // 不行同返回0
        return 0;
    }


}
